using System;
using System.Collections.Generic;
using System.Linq;
using MT5Trade.Models.MarketData;

namespace MT5Trade.Models
{

    /// <summary>
    /// 动态对冲调整器
    /// 根据市场条件和风险指标动态调整对冲策略
    /// </summary>
    public class DynamicHedgeAdjuster
    {
        #region 常量定义

        // 调整阈值
        public const double DELTA_THRESHOLD = 0.05;           // Delta变化阈值（5%）
        public const double GAMMA_THRESHOLD = 0.02;           // Gamma变化阈值（2%）
        public const double VOLATILITY_THRESHOLD = 0.1;       // 波动率变化阈值（10%）
        public const double PNL_THRESHOLD = 0.02;            // 损益阈值（2%）
        
        // 调整频率限制
        public const int MIN_ADJUSTMENT_INTERVAL_MINUTES = 15;  // 最小调整间隔（分钟）
        public const int MAX_ADJUSTMENTS_PER_DAY = 10;         // 每日最大调整次数
        
        // 对冲比例范围
        public const double MIN_HEDGE_RATIO = 0.2;            // 最小对冲比例
        public const double MAX_HEDGE_RATIO = 1.5;            // 最大对冲比例
        public const double OPTIMAL_HEDGE_RATIO = 1.0;        // 最优对冲比例

        #endregion

        #region 调整策略枚举

        /// <summary>
        /// 对冲调整策略
        /// </summary>
        public enum AdjustmentStrategy
        {
            /// <summary>
            /// 不调整
            /// </summary>
            NoAdjustment,

            /// <summary>
            /// 不调整（兼容性别名）
            /// </summary>
            None = NoAdjustment,
            
            /// <summary>
            /// 增加对冲
            /// </summary>
            IncreaseHedge,
            
            /// <summary>
            /// 减少对冲
            /// </summary>
            DecreaseHedge,
            
            /// <summary>
            /// 重新平衡
            /// </summary>
            Rebalance,
            
            /// <summary>
            /// 紧急调整
            /// </summary>
            EmergencyAdjustment
        }

        /// <summary>
        /// 市场状态
        /// </summary>
        public enum MarketCondition
        {
            Calm,           // 平静
            Normal,         // 正常
            Volatile,       // 波动
            Stressed,       // 压力
            Crisis          // 危机
        }

        #endregion

        #region 私有字段

        private readonly List<AdjustmentRecord> _adjustmentHistory;
        private readonly Dictionary<string, HedgePosition> _hedgePositions;
        private DateTime _lastAdjustmentTime;
        private int _dailyAdjustmentCount;
        private DateTime _currentTradingDay;
        private readonly GapHedgingStrategy _gapStrategy;
        private readonly BetaCalculator _betaCalculator;
        private readonly MarketRegimeDetector _marketRegimeDetector;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化动态对冲调整器
        /// </summary>
        public DynamicHedgeAdjuster()
        {
            _adjustmentHistory = new List<AdjustmentRecord>();
            _hedgePositions = new Dictionary<string, HedgePosition>();
            _lastAdjustmentTime = DateTime.MinValue;
            _dailyAdjustmentCount = 0;
            _currentTradingDay = DateTime.UtcNow.Date;
            _gapStrategy = new GapHedgingStrategy();
            _betaCalculator = new BetaCalculator();
            _marketRegimeDetector = new MarketRegimeDetector();
        }

        #endregion

        #region 核心调整方法

        /// <summary>
        /// 动态调整对冲
        /// </summary>
        /// <param name="positionId">持仓ID</param>
        /// <param name="currentSimpleMarketData">当前市场数据</param>
        /// <returns>调整结果</returns>
        public AdjustmentResult AdjustHedge(string positionId, SimpleMarketData currentSimpleMarketData)
        {
            // 重置每日计数器
            if (DateTime.UtcNow.Date > _currentTradingDay)
            {
                _currentTradingDay = DateTime.UtcNow.Date;
                _dailyAdjustmentCount = 0;
            }
            
            // 获取或创建对冲持仓
            if (!_hedgePositions.TryGetValue(positionId, out var hedgePosition))
            {
                hedgePosition = new HedgePosition
                {
                    PositionId = positionId,
                    CreatedAt = DateTime.UtcNow
                };
                _hedgePositions[positionId] = hedgePosition;
            }
            
            // 判断是否需要调整
            var adjustmentNeed = RequiresAdjustment(hedgePosition, currentSimpleMarketData);
            
            if (!adjustmentNeed.RequiresAdjustment)
            {
                return new AdjustmentResult
                {
                    Strategy = AdjustmentStrategy.NoAdjustment,
                    Success = true,
                    Message = "无需调整",
                    Timestamp = DateTime.UtcNow
                };
            }
            
            // 检查调整限制
            if (!CanAdjust())
            {
                return new AdjustmentResult
                {
                    Strategy = AdjustmentStrategy.NoAdjustment,
                    Success = false,
                    Message = "达到调整限制",
                    Timestamp = DateTime.UtcNow
                };
            }
            
            // 确定调整策略
            var strategy = DetermineAdjustmentStrategy(hedgePosition, currentSimpleMarketData, adjustmentNeed);
            
            // 执行调整
            var result = ExecuteHedgeAdjustment(hedgePosition, currentSimpleMarketData, strategy);
            
            // 记录调整历史
            RecordAdjustment(positionId, strategy, result);
            
            return result;
        }

        /// <summary>
        /// 判断是否需要调整
        /// </summary>
        private AdjustmentNeed RequiresAdjustment(HedgePosition position, SimpleMarketData marketData)
        {
            var need = new AdjustmentNeed();
            
            // 1. Delta变化检查
            double currentDelta = CalculateCurrentDelta(position, marketData);
            double deltaChange = Math.Abs(currentDelta - position.LastDelta);
            if (deltaChange > DELTA_THRESHOLD)
            {
                need.RequiresAdjustment = true;
                need.DeltaTrigger = true;
                need.DeltaChange = deltaChange;
            }
            
            // 2. Gamma风险检查
            double currentGamma = CalculateCurrentGamma(position, marketData);
            if (Math.Abs(currentGamma) > GAMMA_THRESHOLD)
            {
                need.RequiresAdjustment = true;
                need.GammaTrigger = true;
                need.GammaValue = currentGamma;
            }
            
            // 3. 波动率变化检查
            double volatilityChange = Math.Abs(marketData.Volatility - position.LastVolatility) / 
                                     Math.Max(0.01, position.LastVolatility);
            if (volatilityChange > VOLATILITY_THRESHOLD)
            {
                need.RequiresAdjustment = true;
                need.VolatilityTrigger = true;
                need.VolatilityChange = volatilityChange;
            }
            
            // 4. 损益检查
            double unrealizedPnL = CalculateUnrealizedPnL(position, marketData);
            double pnlPercentage = Math.Abs(unrealizedPnL) / Math.Max(1, position.InitialValue);
            if (pnlPercentage > PNL_THRESHOLD)
            {
                need.RequiresAdjustment = true;
                need.PnLTrigger = true;
                need.PnLPercentage = pnlPercentage;
            }
            
            // 5. 缺口检查
            if (marketData.HasGap)
            {
                var gapData = _gapStrategy.IdentifyGap(
                    marketData.PreviousClose,
                    marketData.CurrentOpen,
                    marketData.CurrentHigh,
                    marketData.CurrentLow,
                    marketData.PreviousVolume,
                    marketData.CurrentVolume);
                    
                if (gapData.Type != GapType.None)
                {
                    need.RequiresAdjustment = true;
                    need.GapTrigger = true;
                    need.GapType = gapData.Type;
                }
            }
            
            // 6. 市场状态检查
            var marketCondition = AssessMarketCondition(marketData);
            if (marketCondition >= MarketCondition.Stressed)
            {
                need.RequiresAdjustment = true;
                need.MarketStressTrigger = true;
                need.MarketCondition = marketCondition;
            }
            
            return need;
        }

        /// <summary>
        /// 确定调整策略
        /// </summary>
        private AdjustmentStrategy DetermineAdjustmentStrategy(
            HedgePosition position, 
            SimpleMarketData marketData,
            AdjustmentNeed adjustmentNeed)
        {
            // 紧急情况优先
            if (adjustmentNeed.MarketCondition == MarketCondition.Crisis ||
                adjustmentNeed.PnLPercentage > 0.05) // 损失超过5%
            {
                return AdjustmentStrategy.EmergencyAdjustment;
            }
            
            // 缺口情况
            if (adjustmentNeed.GapTrigger)
            {
                switch (adjustmentNeed.GapType)
                {
                    case GapType.Breakaway:
                    case GapType.Continuation:
                        return AdjustmentStrategy.IncreaseHedge;
                    case GapType.Exhaustion:
                        return AdjustmentStrategy.DecreaseHedge;
                    default:
                        return AdjustmentStrategy.Rebalance;
                }
            }
            
            // Delta/Gamma触发
            if (adjustmentNeed.DeltaTrigger || adjustmentNeed.GammaTrigger)
            {
                double currentHedgeRatio = position.CurrentHedgeRatio;
                double targetHedgeRatio = CalculateTargetHedgeRatio(position, marketData);
                
                if (targetHedgeRatio > currentHedgeRatio * 1.1)
                {
                    return AdjustmentStrategy.IncreaseHedge;
                }
                else if (targetHedgeRatio < currentHedgeRatio * 0.9)
                {
                    return AdjustmentStrategy.DecreaseHedge;
                }
                else
                {
                    return AdjustmentStrategy.Rebalance;
                }
            }
            
            // 波动率触发
            if (adjustmentNeed.VolatilityTrigger)
            {
                if (adjustmentNeed.VolatilityChange > 0)
                {
                    return AdjustmentStrategy.IncreaseHedge; // 波动率上升，增加对冲
                }
                else
                {
                    return AdjustmentStrategy.DecreaseHedge; // 波动率下降，减少对冲
                }
            }
            
            // 默认重新平衡
            return AdjustmentStrategy.Rebalance;
        }

        /// <summary>
        /// 执行对冲调整
        /// </summary>
        private AdjustmentResult ExecuteHedgeAdjustment(
            HedgePosition position,
            SimpleMarketData marketData,
            AdjustmentStrategy strategy)
        {
            var result = new AdjustmentResult
            {
                Strategy = strategy,
                Timestamp = DateTime.UtcNow,
                OldHedgeRatio = position.CurrentHedgeRatio
            };
            
            try
            {
                double newHedgeRatio = position.CurrentHedgeRatio;
                
                switch (strategy)
                {
                    case AdjustmentStrategy.IncreaseHedge:
                        newHedgeRatio = Math.Min(MAX_HEDGE_RATIO, 
                            position.CurrentHedgeRatio * 1.2);
                        result.Message = "增加对冲比例";
                        break;
                        
                    case AdjustmentStrategy.DecreaseHedge:
                        newHedgeRatio = Math.Max(MIN_HEDGE_RATIO, 
                            position.CurrentHedgeRatio * 0.8);
                        result.Message = "减少对冲比例";
                        break;
                        
                    case AdjustmentStrategy.Rebalance:
                        newHedgeRatio = CalculateTargetHedgeRatio(position, marketData);
                        result.Message = "重新平衡对冲";
                        break;
                        
                    case AdjustmentStrategy.EmergencyAdjustment:
                        newHedgeRatio = MAX_HEDGE_RATIO; // 最大对冲
                        result.Message = "紧急调整至最大对冲";
                        break;
                        
                    default:
                        result.Message = "无需调整";
                        break;
                }
                
                // 更新持仓
                position.CurrentHedgeRatio = newHedgeRatio;
                position.LastDelta = CalculateCurrentDelta(position, marketData);
                position.LastVolatility = marketData.Volatility;
                position.LastAdjustmentTime = DateTime.UtcNow;
                position.AdjustmentCount++;
                
                // 计算调整成本
                result.AdjustmentCost = CalculateAdjustmentCost(
                    result.OldHedgeRatio, 
                    newHedgeRatio, 
                    position.PositionSize);
                
                result.NewHedgeRatio = newHedgeRatio;
                result.Success = true;
                
                // 更新计数器
                _lastAdjustmentTime = DateTime.UtcNow;
                _dailyAdjustmentCount++;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = $"调整失败: {ex.Message}";
            }
            
            return result;
        }

        #endregion

        #region 辅助计算方法

        /// <summary>
        /// 计算当前Delta
        /// </summary>
        private double CalculateCurrentDelta(HedgePosition position, SimpleMarketData marketData)
        {
            // 简化的Delta计算（实际应根据期权定价模型）
            double priceSensitivity = position.PositionSize * marketData.CurrentPrice / 
                                     Math.Max(1, position.InitialValue);
            return priceSensitivity;
        }

        /// <summary>
        /// 计算当前Gamma
        /// </summary>
        private double CalculateCurrentGamma(HedgePosition position, SimpleMarketData marketData)
        {
            // 简化的Gamma计算（Delta的变化率）
            double deltaChange = 0.01; // 1%的价格变化
            double priceUp = marketData.CurrentPrice * (1 + deltaChange);
            double priceDown = marketData.CurrentPrice * (1 - deltaChange);
            
            // 这里应该使用期权定价模型，简化处理
            double gamma = (priceUp - priceDown) / (2 * marketData.CurrentPrice * deltaChange);
            return gamma * position.PositionSize / 1000; // 归一化
        }

        /// <summary>
        /// 计算未实现损益
        /// </summary>
        private double CalculateUnrealizedPnL(HedgePosition position, SimpleMarketData marketData)
        {
            double currentValue = position.PositionSize * marketData.CurrentPrice;
            return currentValue - position.InitialValue;
        }

        /// <summary>
        /// 计算目标对冲比例
        /// </summary>
        private double CalculateTargetHedgeRatio(HedgePosition position, SimpleMarketData marketData)
        {
            // 基础对冲比例
            double baseRatio = OPTIMAL_HEDGE_RATIO;
            
            // 根据波动率调整
            double volatilityAdjustment = marketData.Volatility / 0.2; // 假设20%为基准波动率
            
            // 根据市场状态调整
            var marketCondition = AssessMarketCondition(marketData);
            double conditionMultiplier = 1.0;
            switch (marketCondition)
            {
                case MarketCondition.Calm:
                    conditionMultiplier = 0.8;
                    break;
                case MarketCondition.Normal:
                    conditionMultiplier = 1.0;
                    break;
                case MarketCondition.Volatile:
                    conditionMultiplier = 1.2;
                    break;
                case MarketCondition.Stressed:
                    conditionMultiplier = 1.4;
                    break;
                case MarketCondition.Crisis:
                    conditionMultiplier = 1.5;
                    break;
            }
            
            double targetRatio = baseRatio * volatilityAdjustment * conditionMultiplier;
            
            // 限制范围
            return Math.Max(MIN_HEDGE_RATIO, Math.Min(MAX_HEDGE_RATIO, targetRatio));
        }

        /// <summary>
        /// 评估市场状态
        /// </summary>
        private MarketCondition AssessMarketCondition(SimpleMarketData marketData)
        {
            // 基于波动率和其他指标评估市场状态
            if (marketData.Volatility < 0.1)
                return MarketCondition.Calm;
            else if (marketData.Volatility < 0.2)
                return MarketCondition.Normal;
            else if (marketData.Volatility < 0.3)
                return MarketCondition.Volatile;
            else if (marketData.Volatility < 0.5)
                return MarketCondition.Stressed;
            else
                return MarketCondition.Crisis;
        }

        /// <summary>
        /// 计算调整成本
        /// </summary>
        private double CalculateAdjustmentCost(double oldRatio, double newRatio, double positionSize)
        {
            double ratioChange = Math.Abs(newRatio - oldRatio);
            double transactionCost = positionSize * ratioChange * 0.0002; // 假设2个基点的交易成本
            double slippage = positionSize * ratioChange * 0.0001; // 假设1个基点的滑点
            return transactionCost + slippage;
        }

        /// <summary>
        /// 检查是否可以调整
        /// </summary>
        private bool CanAdjust()
        {
            // 检查调整频率限制
            var timeSinceLastAdjustment = DateTime.UtcNow - _lastAdjustmentTime;
            if (timeSinceLastAdjustment.TotalMinutes < MIN_ADJUSTMENT_INTERVAL_MINUTES)
            {
                return false;
            }
            
            // 检查每日调整次数限制
            if (_dailyAdjustmentCount >= MAX_ADJUSTMENTS_PER_DAY)
            {
                return false;
            }
            
            return true;
        }

        /// <summary>
        /// 记录调整历史
        /// </summary>
        private void RecordAdjustment(string positionId, AdjustmentStrategy strategy, AdjustmentResult result)
        {
            _adjustmentHistory.Add(new AdjustmentRecord
            {
                PositionId = positionId,
                Strategy = strategy,
                Result = result,
                Timestamp = DateTime.UtcNow
            });
            
            // 限制历史记录大小
            if (_adjustmentHistory.Count > 1000)
            {
                _adjustmentHistory.RemoveRange(0, 100);
            }
        }

        #endregion

        #region 统计方法

        /// <summary>
        /// 获取调整统计
        /// </summary>
        public AdjustmentStatistics GetStatistics()
        {
            return new AdjustmentStatistics
            {
                TotalAdjustments = _adjustmentHistory.Count,
                DailyAdjustments = _dailyAdjustmentCount,
                SuccessfulAdjustments = _adjustmentHistory.Count(r => r.Result.Success),
                FailedAdjustments = _adjustmentHistory.Count(r => !r.Result.Success),
                TotalCost = _adjustmentHistory.Sum(r => r.Result.AdjustmentCost),
                AverageHedgeRatio = _hedgePositions.Values.Average(p => p.CurrentHedgeRatio),
                LastAdjustmentTime = _lastAdjustmentTime
            };
        }

        /// <summary>
        /// 基于波动率调整对冲比例
        /// 根据当前市场波动率动态调整对冲策略
        /// </summary>
        /// <param name="hedgeRatio">当前对冲比例</param>
        /// <param name="currentVolatility">当前市场波动率</param>
        /// <returns>调整后的结果</returns>
        public AdjustmentResult AdjustForVolatility(double hedgeRatio, double currentVolatility)
        {
            // 计算波动率调整因子
            double volatilityFactor = 1.0;
            if (currentVolatility > 0.3) // 高波动率
            {
                volatilityFactor = 1.2; // 增加对冲
            }
            else if (currentVolatility < 0.1) // 低波动率
            {
                volatilityFactor = 0.8; // 减少对冲
            }

            // 计算调整后的对冲比例
            double adjustedRatio = hedgeRatio * volatilityFactor;

            // 确保在有效范围内
            adjustedRatio = Math.Max(MIN_HEDGE_RATIO, Math.Min(MAX_HEDGE_RATIO, adjustedRatio));

            // 判断调整策略
            AdjustmentStrategy strategy = AdjustmentStrategy.NoAdjustment;
            if (Math.Abs(adjustedRatio - hedgeRatio) > DELTA_THRESHOLD)
            {
                strategy = adjustedRatio > hedgeRatio ?
                    AdjustmentStrategy.IncreaseHedge : AdjustmentStrategy.DecreaseHedge;
            }

            return new AdjustmentResult
            {
                Success = true,
                NewHedgeRatio = adjustedRatio,
                OldHedgeRatio = hedgeRatio,
                Strategy = strategy,
                AdjustmentCost = Math.Abs(adjustedRatio - hedgeRatio) * 0.001, // 估算调整成本
                Message = $"波动率调整: {currentVolatility:F3}",
                Timestamp = DateTime.Now
            };
        }

        #endregion

        #region 兼容性方法

        /// <summary>
        /// 简化的对冲调整方法（用于测试）
        /// </summary>
        /// <param name="currentHedgeRatio">当前对冲比例</param>
        /// <param name="targetHedgeRatio">目标对冲比例</param>
        /// <param name="tolerance">容忍度</param>
        /// <returns>调整结果</returns>
        public AdjustmentResult AdjustHedge(double currentHedgeRatio, double targetHedgeRatio, double tolerance)
        {
            var diff = Math.Abs(targetHedgeRatio - currentHedgeRatio);

            if (diff <= tolerance)
            {
                return new AdjustmentResult
                {
                    Strategy = AdjustmentStrategy.None,
                    Success = true,
                    Message = "在容忍范围内，无需调整",
                    OldHedgeRatio = currentHedgeRatio,
                    NewHedgeRatio = currentHedgeRatio,
                    AdjustmentCost = 0,
                    Timestamp = DateTime.Now
                };
            }

            var strategy = targetHedgeRatio > currentHedgeRatio ?
                AdjustmentStrategy.IncreaseHedge : AdjustmentStrategy.DecreaseHedge;

            return new AdjustmentResult
            {
                Strategy = strategy,
                Success = true,
                Message = "需要调整对冲比例",
                OldHedgeRatio = currentHedgeRatio,
                NewHedgeRatio = targetHedgeRatio,
                AdjustmentCost = diff * 0.001,
                Timestamp = DateTime.Now
            };
        }

        /// <summary>
        /// 根据缺口调整对冲
        /// </summary>
        /// <param name="currentHedgeRatio">当前对冲比例</param>
        /// <param name="gap">缺口数据</param>
        /// <returns>调整结果</returns>
        public AdjustmentResult AdjustForGap(double currentHedgeRatio, GapHedgeData gap)
        {
            if (gap == null)
            {
                return new AdjustmentResult
                {
                    Strategy = AdjustmentStrategy.None,
                    Success = false,
                    Message = "缺口数据为空",
                    OldHedgeRatio = currentHedgeRatio,
                    NewHedgeRatio = currentHedgeRatio,
                    AdjustmentCost = 0,
                    Timestamp = DateTime.Now
                };
            }

            double targetRatio = currentHedgeRatio;
            AdjustmentStrategy strategy = AdjustmentStrategy.None;

            // 根据缺口类型调整
            switch (gap.Type)
            {
                case GapType.Breakaway:
                    targetRatio = currentHedgeRatio * 1.3; // 增加30%
                    strategy = AdjustmentStrategy.IncreaseHedge;
                    break;
                case GapType.Exhaustion:
                    targetRatio = currentHedgeRatio * 0.7; // 减少30%
                    strategy = AdjustmentStrategy.DecreaseHedge;
                    break;
                case GapType.Continuation:
                    targetRatio = currentHedgeRatio * 1.1; // 增加10%
                    strategy = AdjustmentStrategy.IncreaseHedge;
                    break;
                default:
                    targetRatio = currentHedgeRatio; // 不变
                    break;
            }

            return new AdjustmentResult
            {
                Strategy = strategy,
                Success = true,
                Message = $"根据{gap.Type}缺口调整对冲",
                OldHedgeRatio = currentHedgeRatio,
                NewHedgeRatio = targetRatio,
                AdjustmentCost = Math.Abs(targetRatio - currentHedgeRatio) * 0.001,
                Timestamp = DateTime.Now
            };
        }

        /// <summary>
        /// 根据市场状态调整敞口比例
        /// 震荡市场优化版本
        /// </summary>
        public double AdjustGapRatio(double currentGapRatio, SimpleMarketData marketData)
        {
            // 检测市场状态
            var regimeResult = _marketRegimeDetector.DetectMarketRegime(marketData);

            // 计算预期胜率
            double winProbability = _marketRegimeDetector.CalculateWinProbability(regimeResult);

            // 根据市场状态和胜率调整敞口
            double optimalGapRatio = CalculateOptimalGapRatio(
                regimeResult.Regime,
                winProbability,
                marketData.Volatility);

            // 记录调整决策
            LogGapAdjustment(currentGapRatio, optimalGapRatio, regimeResult);

            return optimalGapRatio;
        }

        /// <summary>
        /// 计算最优敞口比例
        /// </summary>
        private double CalculateOptimalGapRatio(
            MarketRegimeDetector.MarketRegime regime,
            double winProbability,
            double volatility)
        {
            double baseGapRatio = 0.0;

            switch (regime)
            {
                case MarketRegimeDetector.MarketRegime.HighFrequencyOscillation:
                    // 高频震荡市场
                    if (Math.Abs(winProbability - 0.5) < 0.05) // 胜率接近50%
                    {
                        baseGapRatio = 0.0; // 完全对冲，零敞口
                    }
                    else if (winProbability > 0.55)
                    {
                        baseGapRatio = 0.02; // 2%小敞口试探
                    }
                    else
                    {
                        baseGapRatio = 0.0; // 保守策略，零敞口
                    }
                    break;

                case MarketRegimeDetector.MarketRegime.StrongTrend:
                    // 强趋势市场
                    if (winProbability > 0.65)
                    {
                        baseGapRatio = 0.15; // 15%敞口
                    }
                    else if (winProbability > 0.55)
                    {
                        baseGapRatio = 0.10; // 10%敞口
                    }
                    else
                    {
                        baseGapRatio = 0.05; // 5%敞口
                    }
                    break;

                case MarketRegimeDetector.MarketRegime.WeakTrend:
                    // 弱趋势市场
                    if (winProbability > 0.55)
                    {
                        baseGapRatio = 0.08; // 8%敞口
                    }
                    else
                    {
                        baseGapRatio = 0.03; // 3%敞口
                    }
                    break;

                case MarketRegimeDetector.MarketRegime.LowVolatilityRanging:
                    // 低波动横盘
                    baseGapRatio = 0.01; // 1%最小敞口
                    break;

                default:
                    // 未知状态，保守处理
                    baseGapRatio = 0.0;
                    break;
            }

            // 根据波动率进一步调整
            if (volatility > 0.3) // 高波动
            {
                baseGapRatio *= 0.3; // 大幅降低到30%
            }
            else if (volatility > 0.2) // 中等波动
            {
                baseGapRatio *= 0.6; // 降低到60%
            }
            else if (volatility > 0.15) // 较低波动
            {
                baseGapRatio *= 0.8; // 略减到80%
            }

            // 确保在合理范围内
            return Math.Max(0, Math.Min(0.2, baseGapRatio)); // 最大20%敞口
        }

        /// <summary>
        /// 记录敞口调整日志
        /// </summary>
        private void LogGapAdjustment(
            double oldGap,
            double newGap,
            MarketRegimeResult regimeResult)
        {
            // 这里可以添加日志记录逻辑
            var logMessage = $"敞口调整: {oldGap:P1} -> {newGap:P1}, " +
                            $"市场状态: {regimeResult.Regime}, " +
                            $"置信度: {regimeResult.Confidence:P0}";

            // 可以将日志写入文件或发送到监控系统
            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {logMessage}");
        }

        #endregion
    }

    #region 数据结构定义

    /// <summary>
    /// 简单市场数据（用于动态对冲调整器）
    /// </summary>
    public class SimpleMarketData
    {
        // 现有市场数据字段
        public double CurrentPrice { get; set; }
        public double PreviousClose { get; set; }
        public double CurrentOpen { get; set; }
        public double CurrentHigh { get; set; }
        public double CurrentLow { get; set; }
        public double CurrentVolume { get; set; }
        public double PreviousVolume { get; set; }
        public double Volatility { get; set; }
        public bool HasGap { get; set; }
        public DateTime Timestamp { get; set; }

        // 套利系统新增字段
        public double Spread { get; set; }                    // 当前点差（美元）
        public double AverageStopLoss { get; set; }           // 平均止损距离（点数）
        public double RecentWinRate { get; set; }             // 近期实际胜率
        public double MainAccountEquity { get; set; }         // 主账户净值
        public double BonusAmount { get; set; }               // 剩余赠金金额
        public double FollowerMarginLevel { get; set; }       // 从账户保证金水平
        public double MainLossProbability { get; set; }       // 主账户预期亏损概率
        public TradingMode Mode { get; set; }                 // 交易模式
    }

    /// <summary>
    /// 交易模式枚举
    /// </summary>
    public enum TradingMode
    {
        StandardHedge,      // 标准对冲
        BonusArbitrage     // 赠金套利
    }

    /// <summary>
    /// 对冲持仓
    /// </summary>
    public class HedgePosition
    {
        public string PositionId { get; set; }
        public double PositionSize { get; set; }
        public double InitialValue { get; set; }
        public double CurrentHedgeRatio { get; set; }
        public double LastDelta { get; set; }
        public double LastVolatility { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime LastAdjustmentTime { get; set; }
        public int AdjustmentCount { get; set; }
    }

    /// <summary>
    /// 调整需求
    /// </summary>
    public class AdjustmentNeed
    {
        public bool RequiresAdjustment { get; set; }
        public bool DeltaTrigger { get; set; }
        public double DeltaChange { get; set; }
        public bool GammaTrigger { get; set; }
        public double GammaValue { get; set; }
        public bool VolatilityTrigger { get; set; }
        public double VolatilityChange { get; set; }
        public bool PnLTrigger { get; set; }
        public double PnLPercentage { get; set; }
        public bool GapTrigger { get; set; }
        public GapType GapType { get; set; }
        public bool MarketStressTrigger { get; set; }
        public DynamicHedgeAdjuster.MarketCondition MarketCondition { get; set; }
    }

    /// <summary>
    /// 调整结果
    /// </summary>
    public class AdjustmentResult
    {
        public DynamicHedgeAdjuster.AdjustmentStrategy Strategy { get; set; }
        public bool Success { get; set; }
        public string Message { get; set; }
        public double OldHedgeRatio { get; set; }
        public double NewHedgeRatio { get; set; }
        public double AdjustmentCost { get; set; }
        public DateTime Timestamp { get; set; }

        // 兼容性属性
        public bool RequiresAdjustment => Strategy != DynamicHedgeAdjuster.AdjustmentStrategy.None;
        public double AdjustmentAmount => NewHedgeRatio - OldHedgeRatio;
    }

    /// <summary>
    /// 调整记录
    /// </summary>
    public class AdjustmentRecord
    {
        public string PositionId { get; set; }
        public DynamicHedgeAdjuster.AdjustmentStrategy Strategy { get; set; }
        public AdjustmentResult Result { get; set; }
        public DateTime Timestamp { get; set; }
    }

    /// <summary>
    /// 调整统计
    /// </summary>
    public class AdjustmentStatistics
    {
        public int TotalAdjustments { get; set; }
        public int DailyAdjustments { get; set; }
        public int SuccessfulAdjustments { get; set; }
        public int FailedAdjustments { get; set; }
        public double TotalCost { get; set; }
        public double AverageHedgeRatio { get; set; }
        public DateTime LastAdjustmentTime { get; set; }
    }

    #endregion
}